#include <dirent.h>
#include <vfs.h>
#include <malloc.h>
#include <errno.h>
#include <string.h>

struct __dirstream
{
    int fd;
};

DIR *opendir(const char *__name)
{
    int fd = vfs_opendir(__name);

    if (fd < 0)
        return NULL;

    struct __dirstream *s = malloc(sizeof(DIR));

    if (!s)
        return NULL;
    s->fd = fd;
    return s;
}
int closedir(DIR *__dirp)
{
    if (!__dirp)
        return -1;
    vfs_closedir(__dirp->fd);

    free(__dirp);

    return 0;
}

static struct dirent __dir;

struct dirent *readdir(DIR *__dirp)
{
    errno = 0;
    if (!__dirp)
        return NULL;
    struct vfs_dirent_t *dir = malloc(sizeof(struct vfs_dirent_t));
    int ret = vfs_readdir(__dirp->fd, dir);

    if (ret)
    {
        errno = ret;
        return NULL;
    }

    memcpy(__dir.d_name, dir->d_name, sizeof(dir->d_name));
    __dir.d_off = dir->d_off;
    __dir.d_reclen = dir->d_reclen;
    __dir.d_type = dir->d_type;
    return &__dir;
}